const Base = require('./base.js'),
	userModel = think.model('user'),
	errorInfo = require('../config/error-info.js');

module.exports = class extends Base {
	/**
	 * @author: ares
	 * @date: 2018/6/1 15:56
	 * @description: 用户登录
	 */
	async loginAction() {
		let account = this.post('account'),
			password = this.post('password'),
			token = this.ctx.state.token,
			userInfo = await userModel.getLoginInfo(account, password);

		if (think.isEmpty(userInfo)) {
			return this.fail(...errorInfo.msg1008, '用户或密码错误');
		} else {
			let loginInfo = {
				userId: userInfo._id,
				token: token,
				ip: this.ip,
				loginTime: think.datetime(+new Date)
			};
			//记录登录日志
			await userModel.recordLogin(loginInfo);
			//设置session
			await this.session('auth', token);
			//设置cache
			await this.cache(`token-${account}`, token);
			return this.success({token, userInfo});
		}
	}

	/**
	 * @author: ares
	 * @date: 2019/4/10 11:39
	 * @description: 退出登录
	 * @returns {Promise.<*>}
	 */
	async logoutAction() {
		let token = this.header('token'),
			data = {
				token: token,
				logoutTime: think.datetime(+new Date)
			};
		//记录退出登录时间
		await userModel.recordLogin(data,true);
		let currentAccount = this.ctx.state.currentUser.account;
		//清除缓存
		await this.cache(`token-${currentAccount}`, null);
		//清除session
		await this.session('auth', null);
		return this.success();
	}
};
